package com.sgb.kjwl.view.ui.adapter.base;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatRadioButton;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.databinding.BindingAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.harisucici.jetpackbase.view.HBaseAdapter;
import com.sgb.kjwl.R;
import com.sgb.kjwl.view.widget.SwitchButton;
import com.sgb.kjwl.view.widget.TagTextView;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AppRecyclerBinding {

    @BindingAdapter(value = {"setSpanCount"})
    public static void setSpanCount(RecyclerView recyclerView, int spanCount) {
        if (recyclerView != null) {
            if (recyclerView.getLayoutManager() == null || !(recyclerView.getLayoutManager() instanceof GridLayoutManager)) {
                recyclerView.setLayoutManager(new GridLayoutManager(recyclerView.getContext(), spanCount));
            } else {
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    ((GridLayoutManager) recyclerView.getLayoutManager()).setSpanCount(spanCount);
                }
            }
        }
    }

    @BindingAdapter({"companyAvatarUrl"})
    public static void companyAvatarUrl(ImageView imageView, String url) {
        RequestOptions requestOptions = new RequestOptions()
                .override(Target.SIZE_ORIGINAL)
                .placeholder(R.mipmap.company_zhanwei)
                .fallback(R.mipmap.company_zhanwei)
                .error(R.mipmap.company_zhanwei);

        Glide.with(imageView.getContext())
                .load(url)
                .apply(requestOptions)
                .into(imageView);

    }

//    @BindingAdapter({"substringText"})
//    public static void substringTextView(ImageView imageView, String s) {
//        LogUtils.d("substringTextView s=" + s);
//        if (TextUtils.isEmpty(s)) {
//            return;
//        }
//        if (s.contains(",")) {
//            String[] stringList = s.split(",");
//            AvatarLoadingUtils.setAvatar(imageView, Arrays.asList(stringList));
//        } else {
//            final ArrayList<String> strings = new ArrayList<>();
//            if (TextUtils.isEmpty(s)) {
//                strings.add("-");
//            } else {
//                if (s.length() >= 3) {
//                    strings.add(s.substring(s.length() - 2, s.length()));
//                } else {
//                    strings.add(s);
//                }
//            }
//            AvatarLoadingUtils.setAvatar(imageView, strings);
//        }
//    }

    @BindingAdapter({"imageBitmap"})
    public static void loadImage(ImageView imageView, Bitmap bitmap) {
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(R.drawable.icon_no_logo).fallback(R.drawable.icon_no_logo).error(R.drawable.icon_no_logo);
        Glide.with(imageView.getContext()).load(bitmap).apply(requestOptions).into(imageView);
    }


    @BindingAdapter(value = {"isDefault", "address"}, requireAll = true)
    public static void setTagText(TagTextView textView, Boolean b, String address) {
        List<String> tags = new ArrayList<>();
        if (b) {
            tags.add("默认");
        }
        textView.setContentAndTag(address, tags);
    }

    @BindingAdapter({"isDefault"})
    public static void setTagType(AppCompatRadioButton appCompatRadioButton, Boolean b) {
        if (b) {
            appCompatRadioButton.setChecked(true);
            appCompatRadioButton.setText("已设为默认");
        } else {
            appCompatRadioButton.setChecked(false);
            appCompatRadioButton.setText("设为默认");
        }
    }

        @BindingAdapter(value = {"adapter", "refreshList"}, requireAll = false)
    public static void bindList(RecyclerView recyclerView, RecyclerView.Adapter adapter, List list) {
        if (recyclerView != null && list != null) {
            if (recyclerView.getAdapter() == null) {
                recyclerView.setAdapter(adapter);
            }
            if (list == null) {
                return;
            }
            if (adapter instanceof HBaseAdapter) {
                ((HBaseAdapter) recyclerView.getAdapter()).refreshData(list);
            }
            if (adapter instanceof RecyclerContract.SimpleContract) {
                ((RecyclerContract.SimpleContract) adapter).onRefresh(list);
            } else if (adapter instanceof RecyclerContract.ExpandableContract) {
                ((RecyclerContract.ExpandableContract) adapter).onRefresh(list);
            } else {
                recyclerView.getAdapter().notifyDataSetChanged();
            }
        }
    }

    @BindingAdapter(value = {"adapter", "refreshList"}, requireAll = false)
    public static void bindMap(RecyclerView recyclerView, RecyclerView.Adapter adapter, Map list) {
        if (recyclerView != null && list != null) {
            if (recyclerView.getAdapter() == null) {
                recyclerView.setAdapter(adapter);
            }
            if (adapter instanceof RecyclerContract.SimpleContract) {
                ((RecyclerContract.SimpleContract) adapter).onRefresh(list);
            } else if (adapter instanceof RecyclerContract.ExpandableContract) {
                ((RecyclerContract.ExpandableContract) adapter).onRefresh(list);
            }
        }
    }

    @BindingAdapter(value = {"adapterX", "refreshListX"}, requireAll = false)
    public static void bindListX(XRecyclerView recyclerView, RecyclerView.Adapter adapter, List list) {
        if (recyclerView != null && list != null) {
            if (recyclerView.getAdapter() == null) {
                recyclerView.setAdapter(adapter);
            }
            if (list == null) {
                return;
            }
            if (adapter instanceof HBaseAdapter) {
                ((HBaseAdapter) recyclerView.getAdapter()).refreshData(list);
            } else {
                recyclerView.getAdapter().notifyDataSetChanged();
            }
        }
    }

    @BindingAdapter(value = {"loadingListener"}, requireAll = false)
    public static void bindXRecyclerListener(XRecyclerView recyclerView, XRecyclerView.LoadingListener loadingListener) {
        recyclerView.setLoadingListener(loadingListener);
    }

    @BindingAdapter({"imgSelectBg"})
    public static void imgSelectBg(ImageView imageView, boolean select) {
        imageView.setSelected(select);
    }

    @BindingAdapter(value = {"imgSelect", "imgSelectNon"}, requireAll = false)
    public static void imgSelectOrNon(ImageView imageView, boolean select, boolean nonSelect) {
        if (nonSelect) {
            imageView.setImageResource(R.mipmap.weidu);
        } else {
            imageView.setImageResource(R.drawable.select_qun_member_img);
        }
        imageView.setSelected(select);
    }

    @BindingAdapter({"selectBg"})
    public static void constraintLayoutSelectBg(ConstraintLayout constraintLayout, boolean select) {
        constraintLayout.setSelected(select);
    }

    @BindingAdapter({"frameSelectBg"})
    public static void frameSelectBg(FrameLayout frameLayout, boolean select) {
        frameLayout.setSelected(select);
    }

    @BindingAdapter(value = {"setUserName", "setNickeName"}, requireAll = false)
    public static void setUserName(TextView textView, String setUserName, String setNickeName) {
        StringBuilder stringBuilder = new StringBuilder();
        if (!TextUtils.isEmpty(setUserName)) {
            stringBuilder.append(setUserName);
        }
        if (!TextUtils.isEmpty(setNickeName)) {
            stringBuilder.append("(" + setNickeName + ")");
        }
        textView.setText(stringBuilder.toString());
    }

    @BindingAdapter({"frameLayoutBg"})
    public static void frameLayoutBg(FrameLayout frameLayout, int id) {
        frameLayout.setBackgroundResource(id);
    }

    @BindingAdapter({"imageUrlVideo"})
    public static void loadImageVideo(ImageView imageView, String url) {
        //加载视频第一帧
        Log.d("loadImageVideo", "loadImageVideo=" + Thread.currentThread().getName());
        Glide.with(imageView.getContext())
                .setDefaultRequestOptions(
                        new RequestOptions()
                                .frame(1000000)
                                .placeholder(R.drawable.icon_no_logo)
                                .fallback(R.drawable.icon_no_logo)
                                .error(R.drawable.icon_no_logo)
                )
                .load(url)
                .into(imageView);
    }

    @BindingAdapter({"constraintLayoutBg"})
    public static void constraintLayoutBg(ConstraintLayout constraintLayout, int bg) {
        constraintLayout.setBackgroundResource(bg);
    }

    @BindingAdapter({"linearLayoutBg"})
    public static void linearLayoutBg(LinearLayout linearLayout, int id) {
        linearLayout.setBackgroundResource(id);

    }

    @BindingAdapter({"imageId1"})
    public static void loadImage1(ImageView imageView, int id) {
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.override(Target.SIZE_ORIGINAL);
        requestOptions.placeholder(R.drawable.icon_no_logo).fallback(R.drawable.icon_no_logo).error(R.drawable.icon_no_logo);
        Glide.with(imageView.getContext()).load(id).apply(requestOptions).into(imageView);
    }

    @BindingAdapter({"key", "text"})
    public static void colorText(TextView tv, String key, String text) {
        if (TextUtils.isEmpty(key)) {
            tv.setText(text);
        } else {
            SpannableString s = new SpannableString(text);
            Pattern p = Pattern.compile(key);
            Matcher m = p.matcher(s);
            tv.setText(text);
            while (m.find()) {
                int start = m.start();
                int end = m.end();
                s.setSpan(new ForegroundColorSpan(Color.parseColor("#007AFF")), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv.setText(s);
            }
        }

    }

    @BindingAdapter({"switchButton"})
    public static void switchButton(SwitchButton imageView, boolean isCheck) {
        imageView.setChecked(isCheck);
    }

    @BindingAdapter("time")
    public static void formatTimeString(TextView textView, long time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd  HH:mm");
        Date date = new Date(time);
        textView.setText("创建于" + simpleDateFormat.format(date));
    }
}
